package com.ksd.web.controller.tool;

public class SubnetMaskConversion {
    public static String convertCidrToDottedDecimal(int cidr) {
        if (cidr < 0 || cidr > 32) {
            throw new IllegalArgumentException("CIDR value should be between 0 and 32");
        }
        long mask = (0xffffffffL << (32 - cidr)) & 0xffffffffL;
        StringBuilder sb = new StringBuilder();
        sb.append((int) (mask >> 24)).append('.');
        sb.append((int) ((mask >> 16) & 0xff)).append('.');
        sb.append((int) ((mask >> 8) & 0xff)).append('.');
        sb.append((int) (mask & 0xff));
        return sb.toString();
    }
    public static int convertToCidr(String subnetMask) {
        String[] parts = subnetMask.split("\\.");
        if (parts.length != 4) {
            throw new IllegalArgumentException("无效的子网掩码格式");
        }
        StringBuilder binaryMask = new StringBuilder();
        for (String part : parts) {
            int num = Integer.parseInt(part);
            String binary = String.format("%8s", Integer.toBinaryString(num)).replace(' ', '0');
            binaryMask.append(binary);
        }
        int cidr = 0;
        for (int i = 0; i < binaryMask.length(); i++) {
            if (binaryMask.charAt(i) == '1') {
                cidr++;
            } else {
                break;
            }
        }
        return cidr;
    }
    public static void main(String[] args) {
        int cidr = 24;
        String dottedDecimal = convertCidrToDottedDecimal(cidr);
        System.out.println(dottedDecimal);
    }
}
